import React, { useState, useRef, useEffect } from 'react';
import { Carousel } from 'antd';
import slider1 from '@/assets/datang/deploy/p1.png';
import slider2 from '@/assets/datang/deploy/p2.png';
import slider3 from '@/assets/datang/deploy/p3.png';
import styles from './index.less';

const sliders = [
  { name: '市场交易', img: slider1 },
  { name: '数字化建设', img: slider2 },
  { name: '新业态应对', img: slider3 },
];
export default () => {
  const carouselRef = useRef();
  const speed = 10 * 1000;

  const [active, setActive] = useState(0);

  useEffect(() => {
    const timer = setInterval(() => {
      const i = active + 1 === sliders.length ? 0 : active + 1;
      setActive(i);
      carouselRef?.current?.goTo(i, true);
    }, speed);
    return () => {
      clearInterval(timer);
    };
  });

  const onChangeDot = (e, i) => {
    e.stopPropagation();
    if (i === active) return;
    setActive(i);
    carouselRef?.current?.goTo(i, true);
  };

  return (
    <div className={styles.container}>
      <div className={styles.myDots}>
        {sliders.map(({ name }, idx) => (
          <div
            key={name}
            className={idx === active ? styles.active : null}
            onClick={(e) => onChangeDot(e, idx)}
          >
            <span>{name}</span>
          </div>
        ))}
      </div>
      <Carousel
        ref={carouselRef}
        dots={{ className: styles.dotsClass }}
        speed={speed}
        afterChange={(i) => {
          i !== active && setActive(i);
        }}
      >
        {sliders.map(({ name, img }) => (
          <div key={name}>
            <img style={{ width: '100%' }} src={img} alt={name} />
          </div>
        ))}
      </Carousel>
    </div>
  );
};
